﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace MassiveBattle.Controller
{
	public abstract partial class BaseController : MonoBehaviour, Manager.IWorker
	{
		public Fsm<EStateMain> FsmMain { get; protected set; }

		public class FsmTransition<T> where T : struct
		{
			private HashSet<T> transitionSet = new HashSet<T>();

			public void AddTransition(params T[] idList)
			{
				foreach (var id in idList)
					transitionSet.Add(id);
			}

			public bool IsCanTransition(T id)
			{
				return transitionSet.Contains(id);
			}
		}

		public class FsmState<T> : FsmTransition<T> where T : struct
		{
			public Action EventStart;
			public Action EventTakeEnd;
		}

		public class Fsm<T> : FsmTransition<T> where T : struct
		{
			private Dictionary<T, FsmState<T>> stateMap = new Dictionary<T, FsmState<T>>();
			public FsmState<T> StateCurrent { get; private set; }

			public FsmState<T> AddState(T id)
			{
				return stateMap[id] = new FsmState<T>();
			}

			public FsmState<T> GetState(T id)
			{
				return stateMap.ContainsKey(id) ? stateMap[id] : null;
			}

			public bool Transit(T id)
			{
				if (!stateMap.ContainsKey(id))
					return false;

				if (!IsCanTransition(id) && !StateCurrent.IsCanTransition(id))
					return false;

				StateCurrent = stateMap[id];

				if (StateCurrent.EventStart != null)
					StateCurrent.EventStart();

				return true;
			}
		}
	}
}
